package service

import (
	"miao/dao"
	"miao/dto"
	"miao/models"
	"miao/util"
	"time"
)

func SaveFile(path string, fileName string) {
	var userDto = util.GetValue("userInfo").(dto.UserDto)
	t := time.Now()
	file := models.SysOSS{
		Id:         util.GenerateSnowflakeId(),
		Url:        path,
		FileName:   fileName,
		DelFlag:    0,
		Creator:    userDto.Id,
		CreateDate: &t,
		Updater:    userDto.Id,
		UpdateDate: &t,
	}
	err := dao.SaveFile(file)
	if err != nil {
		return
	}
}

func PageFile(currentPage int, pageSize int, username string) util.Result {
	files, total, err := dao.PageFile(currentPage, pageSize, username)
	if err != nil {
		return util.Fail(500, err.Error())
	}
	var fileDtos []dto.FileDto
	for file := range files {
		fileDto := dto.FileDto{
			Id:          files[file].Id,
			DownloadUrl: files[file].Url + "download/" + files[file].FileName,
			FileName:    files[file].FileName,
			PreviewUrl:  files[file].Url + "preview/" + files[file].FileName,
		}
		fileDtos = append(fileDtos, fileDto)
	}
	pages := models.PageData{
		Total: total,
		List:  fileDtos,
	}
	return util.Success(pages)
}

func DropFile(id string) util.Result {
	err := dao.DeleteById(id)
	if err != nil {
		return util.Fail(500, err.Error())
	}
	return util.Success(nil)
}
